package com.bamboo.toolbox.core.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

/**
 * @author: luzhiqing
 * @date: 2022-10-19
 **/
@Slf4j
public class HttpUtils {
    public static String post(String url, Object obj) {
        HttpClient client = HttpClient.newHttpClient();
        URI uri = null;
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        HttpRequest request = HttpRequest.newBuilder(uri)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(JsonUtils.toJson(obj)))
                .timeout(Duration.ofSeconds(30))
                .build();
        HttpResponse<String> httpResponse = null;
        try {
            httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            log.error("http请求异常", e);
            throw new RuntimeException(e);
        }
        log.info("http请求url{},结果{}", url, JsonUtils.toJson(httpResponse));
        return httpResponse.body();
    }

}
